package baidu.com.matedemo.pair;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import com.baidu.duer.smartmate.duerlink.bean.DuerlinkError;
import com.baidu.duer.smartmate.out.DuerConstant;
import com.baidu.duer.smartmate.out.DuerDevice;
import com.baidu.duer.smartmate.out.oauth.IResponseCallback;
import com.baidu.duer.smartmate.protocol.dlp.bean.autentication.DeviceCodePairReturnPayload;
import com.baidu.duer.smartmate.proxy.IConnectionListener;
import com.baidu.duer.smartmate.proxy.bean.AuthenticationMessage;
import com.baidu.duer.smartmate.proxy.controller.AuthenticationObserver;


/**
 * Created by niufei01 on 2018/1/31.
 * 普通开发者使用的device code 授权方式，此方案仅能保证设备获取到accessToken，无其他后续功能
 */

public class DeviceCodePair implements IDevicePair, IConnectionListener, AuthenticationObserver {
    private Activity mActivity = null;
    private DuerDevice mDuerDevice = null;
    private IResponseCallback mCallback = null;

    @Override
    public void startPair(Activity activity, DuerDevice duerDevice, IResponseCallback callback) {
        if (activity == null || duerDevice == null || callback == null) {
            return;
        }
        mActivity = activity;
        mDuerDevice = duerDevice;
        mCallback = callback;
        mDuerDevice.getControllerManager().registerAuthenticationObserver(this);
        mDuerDevice.connect(mActivity, this);
    }

    @Override
    public void stopPair() {
        if (mDuerDevice != null) {
            mDuerDevice.getControllerManager().unregisterAuthenticationObserver(this);
        }
    }

    @Override
    public void onConnected() {

    }

    @Override
    public void onLocalConnected() {
        mDuerDevice.getControllerManager().deviceCodePair();
    }

    @Override
    public void onConnectionFailed() {
        mCallback.onError(DuerlinkError.DLP_CONNECT_FAIL.ordinal(),
                DuerlinkError.DLP_CONNECT_FAIL.toString());
        stopPair();
    }

    @Override
    public void onDisconnected() {

    }

    @Override
    public void onDataChanaged(String event, AuthenticationMessage message) {

    }

    @Override
    public void onDeviceCodePairReturn(DeviceCodePairReturnPayload payload) {
        DeviceCodeDialog deviceCodeDialog = new DeviceCodeDialog(mActivity,
                payload.getUserCode(),
                new IResponseCallback() {
                    @Override
                    public void onSuccess() {
                        mCallback.onSuccess();
                        stopPair();
                    }

                    @Override
                    public void onError(long status, String msg) {
                        mCallback.onError(DuerlinkError.OAUTH_FAIL.ordinal(),
                                DuerlinkError.OAUTH_FAIL.toString());
                        stopPair();
                    }
                });
        deviceCodeDialog.show();
    }


    /***
     * 授权框
     */
    public static class DeviceCodeDialog extends Dialog {
        final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
        private IResponseCallback responseCallback;
        private ProgressDialog mSpinner;
        private WebView mWebView;
        private FrameLayout mContent;

        private String URL_DEVICE_CODE = "https://openapi.baidu.com/device?code=%s&display=mobile" +
                "&redirect_uri=oob";

        private String userCode;

        public DeviceCodeDialog(@NonNull Context context, String userCode, IResponseCallback responseCallback) {
            super(context, android.R.style.Theme_Translucent_NoTitleBar);
            this.userCode = userCode;
            this.responseCallback = responseCallback;
        }


        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            if (responseCallback != null) {
                responseCallback.onError(DuerConstant.OAUTH_CANCELLED, "oauth cancel");
            }
            return super.onKeyDown(keyCode, event);
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // 设置ProgressDialog的样式
            mSpinner = new ProgressDialog(getContext());
            mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
            mSpinner.setMessage("Loading...");
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            mContent = new FrameLayout(getContext());

            setUpWebView();
            addContentView(mContent, FILL);
        }

        private void setUpWebView() {
            RelativeLayout webViewContainer = new RelativeLayout(getContext());
            mWebView = new WebView(getContext());
            mWebView.setVerticalScrollBarEnabled(false);
            mWebView.setHorizontalScrollBarEnabled(false);
            mWebView.getSettings().setJavaScriptEnabled(true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }
            mWebView.setWebViewClient(new MWebViewClient());
            mWebView.loadUrl(String.format(URL_DEVICE_CODE, userCode));
            mWebView.setLayoutParams(FILL);
            mWebView.getSettings().setSavePassword(false);
            webViewContainer.addView(mWebView);
            mContent.addView(webViewContainer, FILL);
        }


        private class MWebViewClient extends WebViewClient {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.contains("result=success")) {
                    if (responseCallback != null) {
                        responseCallback.onSuccess();
                    }
                    dismiss();
                    return true;
                } else if (url.contains("result=failure")) {
                    if (responseCallback != null) {
                        responseCallback.onError(0, "oauth failure");
                    }
                    dismiss();
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description,
                                        String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
            }
        }
    }
}
